package cn.egame.extraction;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import cn.egame.client.EGameClientExtV2;
import cn.egame.client.EGameClientV2;
import cn.egame.client.biz.EGameClientBiz;
import cn.egame.common.exception.ExceptionCommonBase;
import cn.egame.common.model.PageData;
import cn.egame.common.util.Utils;
import cn.egame.ext.sw.TerminalUser;
import cn.egame.extraction.pojo.GameStatusInfo;
import cn.egame.extraction.pojo.HdpRptClientV7ModelInfo;
import cn.egame.extraction.service.GameStatusService;
import cn.egame.extraction.service.GameTagLinkService;
import cn.egame.extraction.service.GameTagService;
import cn.egame.extraction.service.HdpRptClientV7ModelService;
import cn.egame.extraction.service.ParameterAppService;
import cn.egame.extraction.service.ReportGameDayDownService;
import cn.egame.extraction.service.UserGameService;
import cn.egame.extraction.util.ConsVar;
import cn.egame.interfaces.EnumType.AppParameterParamType;
import cn.egame.interfaces.EnumType.GameTagType;
import cn.egame.interfaces.EnumType.GameType;
import cn.egame.interfaces.EnumType.SearchSortType;
import cn.egame.interfaces.gc.GameStatus;
import cn.egame.interfaces.gc.GameTagInfo;

public class Server {
    private static Logger logger = Logger.getLogger(Server.class.getName());

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Utils.initLog4j();
        try {
            logger.info("--------------flush v7 cache start----------------");
            flushGameStatus();
            logger.info("<<<<<<<flush---flushGameStatus--->>>>>-----------success-------");
//            flushGameTagLinkRank();
//            logger.info("<<<<<<<flush---flushGameTagLinkRank--->>>>>>>>>>>>-----------success-------");
//            updateReportGameDayDownCountIncr();
//            logger.info("<<<<<<<update ReportGameDayDown------>>>>>>>>>>>>-----------success-------");

            reloadListGameIdByGameTagId();
            logger.info("<<<<<<<update reloadListGameIdByGameTagId------>>>>>>>>>>>>-----------success-------");

            flushSystemAutoSearchTag();
            logger.info("<<<<<<<flush SystemAutoSearchTag------>>>>>>>>>>>>-----------success-------");
//            flushUserGame();
//            logger.info("<<<<<<<flush UserGame------>>>>>>>>>>>>-----------success-------");
            flushListSearchTop50();
            logger.info("<<<<<<<flush flushListSearchTop50------>>>>>>>>>>>>-----------success-------");

//            flushTerminalUser();
//            logger.info("<<<<<<<flush terminalUser------>>>>>>>>>>>>-----------success-------");
            
            logger.info("--------------flush v7 cache end----------------");
        } catch (Exception e) {
            logger.error("",e);
        } finally {
            System.exit(-1);
            
        }
        logger.info("sppend time total : " + (System.currentTimeMillis() - start) / 1000 + "s");
    }

    private static void flushTerminalUser() throws RemoteException {
    	List<HdpRptClientV7ModelInfo> infoList = 
    			HdpRptClientV7ModelService.getInstance().listHdpRptClientV7ModelInfos();
    	for(HdpRptClientV7ModelInfo info : infoList){
    		if(info!=null && !Utils.stringIsNullOrEmpty(info.getModel())
    				&& info.getNumber()>=500){
    			TerminalUser terminalUser = 
    					EGameClientExtV2.getInstance().getTerminalUserByUaCode(0, 0, info.getModel());
    			if(terminalUser!=null){
    				continue;
    			}
    			terminalUser = new TerminalUser(info.getModel(), info.getNumber(), info.getDate());
    			int i = EGameClientExtV2.getInstance().setTerminalUser(0, 0, terminalUser);
    		}
    	}
	}

	private static void flushListSearchTop50() {
        try {
            EGameClientExtV2.getInstance().flushListSearchTop50(0, 0);
        } catch (RemoteException e) {
            logger.error(e);
        }
    }

    private static void flushUserGame() {
        try {
            UserGameService.getInstance().deleteUserGameMore30();
        } catch (ExceptionCommonBase e) {
            logger.error(e);
        } catch (RemoteException e) {
            logger.error(e);
        }

    }

    // gamestatus
    private static void flushGameStatus() {
        try {
            List<Integer> listGid = ReportGameDayDownService.getInstance().listReportGameDayDownGId();
            if (listGid != null && listGid.size() > 0) {
                int i = 0;
                for (Integer gId : listGid) {
                    if (gId <= 0) {
                        continue;
                    }
                    logger.info("ReportGameDayDown:g_id----------" + gId + "-----count = " + i++);
                    GameStatusInfo gameStatus = new GameStatusInfo();
                    gameStatus.setgId(gId);
                    GameStatusService.getInstance().setGameStatus(gameStatus);
                    gameStatus = GameStatusService.getInstance().getGameStatus(gId);
                    ReportGameDayDownService.getInstance().updateReportGameDayDownCountIncr(gId);
                    if(gameStatus !=null){
                    	GameTagLinkService.getInstance().updateGameTagLinkDao(gameStatus);
                    	logger.info("game_status:g_id----------" + gameStatus.getGId() + "-----count = " + i++);
                    }
                }

            }
            PageData pGIds = EGameClientV2.getInstance().pageGameIdByChannelId(0, 0, GameType.mobile, 0, ConsVar.WEBID, 0, 1000, SearchSortType.none);
            List<Integer> gIds = new ArrayList<Integer>();
            if (pGIds != null) {
                gIds = (List<Integer>) pGIds.getContent();
            }

            for (Integer gId : gIds) {
                GameStatus gameStatus = EGameClientV2.getInstance().getGameStatus(0, 0, gId);
                // 页游在线玩人数随机浮动
                int countOnlineWeb = gameStatus.getCountDownTotal() == 0 ? 1000 : gameStatus.getCountDownTotal();
                // 上下浮动50%
                countOnlineWeb = (int) (countOnlineWeb * (new Random().nextDouble() + 0.5));
                GameStatusInfo statustInfo = new GameStatusInfo();
                statustInfo.setgId(gId);
                statustInfo.setCountOnlineWeb(countOnlineWeb);
                GameStatusService.getInstance().updateGameStatus(statustInfo);
            }
            
            // game_statsu
            EGameClientBiz.getInstance().flushGameStatus();
            logger.info("<<<<<<<flushGameStatus to cache------>>>>>>>>>>>>-----------success-------");
        } catch (Exception e) {
            logger.error(e);
        }
    }

    // gamestatus
    private static void flushGameTagLinkRank() {
        try {
            List<GameStatusInfo> lists = GameStatusService.getInstance().listGameStatus();
            if (lists != null && lists.size() > 0) {
                int i = 0;
                for (GameStatusInfo info : lists) {
                    GameTagLinkService.getInstance().updateGameTagLinkDao(info);
                    logger.info("game_status:g_id----------" + info.getGId() + "-----count = " + i++);
                }

            }
        } catch (ExceptionCommonBase e) {
            logger.error(e);
        }
    }

    // 刷新gametaglink排行数据
    // private static void flushGameTagLinkRank() throws ExceptionCommonBase {
    // List<Integer> listGid = ReportGameDayDownService.getInstance()
    // .listReportGameDayDownGId();
    // if (listGid != null && listGid.size() > 0) {
    // for (Integer gId : listGid) {
    // if (gId <= 0) {
    // continue;
    // }
    // GameTagLinkInfo info = new GameTagLinkInfo();
    // info.setgId(gId);
    // GameTagLinkService.getInstance().updateGameTagLinkDao(info);
    // }
    //
    // }
    //
    // }

    // update t_report_game_day_down game_counts_incr to 0

    private static void updateReportGameDayDownCountIncr() {
        try {
            List<Integer> listGid = ReportGameDayDownService.getInstance().listReportGameDayDownGId();
            if (listGid != null && listGid.size() > 0) {
                for (Integer gId : listGid) {
                    if (gId <= 0) {
                        continue;
                    }
                    ReportGameDayDownService.getInstance().updateReportGameDayDownCountIncr(gId);
                }
            }
        } catch (ExceptionCommonBase e) {
            logger.error(e);
        }
    }

    // flush 推荐 ,网游最热,日排行,周排行,月排行,总排行,game_status
    private static void reloadListGameIdByGameTagId() {
        try { // 推荐
            reloadGameByAppParamterParamType(AppParameterParamType.merge_tag_id);
            logger.info("<<<<<<<update AppParameterParamType.merge_tag_id------>>>>>>>>>>>>-----------success-------");
            // 网游最热
            reloadGameByAppParamterParamType(AppParameterParamType.merge_net_tag_id);
            logger.info("<<<<<<<update AppParameterParamType.merge_net_tag_id------>>>>>>>>>>>>-----------success-------");
            // 日排行
            reloadGameByAppParamterParamType(AppParameterParamType.is_rank_day);
            logger.info("<<<<<<<update AppParameterParamType.is_rank_day------>>>>>>>>>>>>-----------success-------");
            // 周排行
            reloadGameByAppParamterParamType(AppParameterParamType.is_rank_week);
            logger.info("<<<<<<<update AppParameterParamType.is_rank_week------>>>>>>>>>>>>-----------success-------");
            // 月排行
            reloadGameByAppParamterParamType(AppParameterParamType.is_rank_month);
            logger.info("<<<<<<<update AppParameterParamType.is_rank_month------>>>>>>>>>>>>-----------success-------");
            // 总排行
            reloadGameByAppParamterParamType(AppParameterParamType.is_rank_total);
            logger.info("<<<<<<<update AppParameterParamType.is_rank_total------>>>>>>>>>>>>-----------success-------");

            // 免费排行
            reloadGameByAppParamterParamType(AppParameterParamType.is_rank_free);
            logger.info("<<<<<<<update AppParameterParamType.is_rank_free------>>>>>>>>>>>>-----------success-------");
        } catch (RemoteException e) {
            logger.error(e);
        }
    }

    private static void reloadGameByAppParamterParamType(AppParameterParamType type) throws ExceptionCommonBase, RemoteException {
        List<Integer> ids = ParameterAppService.getInstance().listAppParameterIdsByParam(type);
        if (ids != null && ids.size() > 0) {
            for (Integer id : ids) {
                int tagId = GameTagService.getInstance().getGameTagId(id + "");
                if (tagId > 0) {
                    EGameClientBiz.getInstance().reloadListGameIdByGameTagId(tagId);
                    logger.info("tagId======" + tagId);
                }
            }
        }
    }

    public static void flushSystemAutoSearchTag() {
        try {
            List<String> lists = EGameClientExtV2.getInstance().listSearchTop50(0, 0);
            List<String> list = new ArrayList<String>();
            List<GameTagInfo> gameTagList = EGameClientV2.getInstance().listGameTagByType(0, 0l, GameTagType.searchTag.value());
           if(gameTagList !=null && gameTagList.size()>0){
               for(GameTagInfo info :gameTagList){
                   list.add(info.getTagName());
               }
           }
            if (lists != null && lists.size() > 0) {
                GameTagService.getInstance().deleteGameTagIdByGameTagType(GameTagType.systemAutoSearchTag);
                GameTagService.getInstance().deleteGameTagIdByGameTagType(GameTagType.first_systemAutoSearchTag);
                GameTagInfo info = null;
                int i = 0;
                for (String str : lists) {
                    if(Utils.stringIsNullOrEmpty(str)){
                        continue;
                    }
                    if (str.length() > 5 || str.trim().matches("[\u4e00-\u9fa5]{1}|[A-Za-z0-9\\s]+") ||  str.trim().matches("\\S+\\s+\\S+")) {
                        continue;
                    }
                    if (list.contains(str) || list.contains(str.trim())) {
                        continue;
                    } else {
                        list.add(str);
                    }

                    int countClick = EGameClientExtV2.getInstance().getSearchCountBySearchName(0, 0, str);
                    info = new GameTagInfo();
                    info.setEnable(1);
                    info.setTagName(str.trim());
                    info.setTagType(GameTagType.systemAutoSearchTag);
                    info.setCountClick(countClick);
                    GameTagService.getInstance().setGameTagInfo(info);
                    i++;
                    if (i == 50) {
                        break;
                    }
                }
            }
            EGameClientBiz.getInstance().reloadListTagIdByTagType(GameTagType.systemAutoSearchTag);
        } catch (RemoteException e) {
            logger.error(e);
        }
    }
}
